//
//  PersonInfoViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/8/23.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "PersonInfoViewController.h"

#import "PwdUpViewController.h"
#import "UpdateNameViewController.h"
#import "UpdatePhoneViewController.h"
#import "SHDZViewController.h"

#import "XJDZViewController.h"
#import "SMRZViewController.h"
#import "XueLiViewController.h"
#import "XueLiDetViewController.h"
#import "JSZViewController.h"
#import "XSZViewController.h"
#import "ResetPayViewController.h"
#import "BankCardViewController.h"
@interface PersonInfoViewController ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    NSArray *array1;//title
    NSMutableArray *array;//det
    UIImageView *imageView;
    UIImagePickerController *imagepc;
    NSString *fileName;
}

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *vcs;

@property (nonatomic,copy)NSString *str2;
@property (nonatomic,copy)NSString *str3;
@property (nonatomic,copy)NSString *str4;
@property (nonatomic,copy)NSString *str5;
@property (nonatomic,copy)NSString *str6;
@property (nonatomic,copy)NSString *str7;
@property (nonatomic,copy)NSString *str8;
@property (nonatomic,copy)NSString *str9;
@property (nonatomic,copy)NSString *str10;
@property (nonatomic,copy)NSString *str11;
@property (nonatomic,copy)NSString *str12;

@property (nonatomic,strong)NSDictionary *datas;

@end

@implementation PersonInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.view.backgroundColor = COLOR_RGB(242, 242, 242, 1);
    
    [self showNav:@"个人资料"];
    array1 = @[@"头像",@"昵称",@"手机号",@"登录密码",@"支付密码",@"银行卡",@"现居地址",@"收货地址",@"学历认证",@"驾驶证",@"行驶证"];
    array = [NSMutableArray array];
    
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    _dic = [accountDefaults objectForKey:@"dic"];
    NSString *phoneString = [NSString stringWithFormat:@"%li",[[_dic objectForKey:@"phone"] integerValue]];
    
    if (![self isNullOrEmpty:phoneString]) {
        phoneString = [phoneString stringByReplacingCharactersInRange:NSMakeRange(3, 5)  withString:@"*****"];
    }else{
        phoneString = @"";
    }
    _str3 = phoneString;
    _str4 = [NSString stringWithFormat:@"******"];
    _str5 = [NSString stringWithFormat:@"******"];
    _str6 = [NSString stringWithFormat:@"去绑定"];
    _str7 = [_dic objectForKey:@"currentsuite"];
    _str8 = [NSString stringWithFormat:@"去填写"];
    _str9 = [NSString stringWithFormat:@""];
    _str10 = @"";
    _str11 = @"";
    NSString *driveback = [_dic objectForKey:@"driveback"];
    if (driveback.length == 0) {
        _str12 = @"去认证";
    }else{
        _str12 = @"";
    }
    
    [array addObject:@""];
    [array addObject:_pickName];
    [array addObject:_str3];
    [array addObject:_str4];
    [array addObject:_str5];
    [array addObject:_str6];
    [array addObject:_str7];
    [array addObject:_str8];
    [array addObject:_str9];
    [array addObject:_str10];
    [array addObject:_str11];
    [array addObject:_str12];
    
    
    [self loadUI];
}

-(void)viewWillAppear:(BOOL)animated{
    NSString *str = [NSString stringWithFormat:@"%@890d69e502d1d37a9e84335ccefece57",[user objectForKey:@"token2"]];
    NSString *token = [LCMD5Tool md5:str];
    
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:token forKey:@"verifyToken"];
    NSString *userid = [NSString stringWithFormat:@"%li",[[user objectForKey:@"userid"] integerValue]] ;
    if (userid.length != 0) {
        [parmas setObject:userid forKey:@"userid"];//int
    }
    
    NSLog(@"parmas:%@",parmas);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *url = [NSString stringWithFormat:@"%@/App/Usercenter/index",urlHead];
    [manager POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"我的res:%@",responseObject);
        
        NSString *status = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"status"] integerValue]];
        if ([status integerValue] == 200) {
            _datas = [responseObject objectForKey:@"content"];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}


- (void)loadUI{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64) style:UITableViewStylePlain];
    _tableView.dataSource = self;//44*10+60
    _tableView.delegate = self;
    _tableView.scrollEnabled = YES;
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:_tableView];
    
}

#pragma -mark UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return array1.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];
    }
    cell.textLabel.text = array1[indexPath.row];
    cell.textLabel.font = [UIFont systemFontOfSize:15.0];
    cell.textLabel.textColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0];
    
    cell.detailTextLabel.text = array[indexPath.row];
    
    cell.detailTextLabel.font = [UIFont systemFontOfSize:13.0];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.row == 0) {
        imageView = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth-50-16-20, 5, 50, 50)];
        imageView.layer.cornerRadius = 25.0;
        imageView.layer.masksToBounds = YES;
        [imageView sd_setImageWithURL:[NSURL URLWithString:_imageUrl] placeholderImage:[UIImage imageNamed:@"thedefaultavatar"]];
        imageView.layer.borderWidth = 1.0;
        imageView.layer.borderColor = [UIColor redColor].CGColor;
        [cell.contentView addSubview:imageView];
    }
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 60.0;
    }else{
        return 44.0;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        [self loadHead];
    }else if (indexPath.row == 1){
        UpdateNameViewController *name = [[UpdateNameViewController alloc] init];
        
        [self.navigationController pushViewController:name animated:YES];
    }else if (indexPath.row == 2){
        UpdatePhoneViewController *phone = [[UpdatePhoneViewController alloc] init];
        [self.navigationController pushViewController:phone animated:YES];
    }else if (indexPath.row == 3){
        PwdUpViewController *pwd = [[PwdUpViewController alloc] init];
        [self.navigationController pushViewController:pwd animated:YES];
    }else if (indexPath.row == 4){
        ResetPayViewController *pay = [[ResetPayViewController alloc] init];
        [self.navigationController pushViewController:pay animated:YES];
        
    }else if (indexPath.row == 5){
        BankCardViewController *bank = [[BankCardViewController alloc] init];
        [self.navigationController pushViewController:bank animated:YES];
    }else if (indexPath.row == 6){
        XJDZViewController *xjdz = [[XJDZViewController alloc] init];
        xjdz.province = [_datas objectForKey:@"currentprovince"];
        xjdz.city = [_datas objectForKey:@"currentcity"];
        xjdz.area = [_datas objectForKey:@"currentdist"];
        xjdz.det = [_datas objectForKey:@"currentsuite"];
        [self.navigationController pushViewController:xjdz animated:YES];
    }else if (indexPath.row == 7){
        SHDZViewController *shdz = [[SHDZViewController alloc] init];
        shdz.state = @"aaa";
        [self.navigationController pushViewController:shdz animated:YES];
    }else if (indexPath.row == 8){
        NSString *education = [_dic objectForKey:@"education"];
        NSLog(@"education:%@",education);
        if (education.length == 0) {
            XueLiViewController *xueli = [[XueLiViewController alloc] init];
            [self.navigationController pushViewController:xueli animated:YES];
        }else{
            XueLiDetViewController *det = [[XueLiDetViewController alloc] init];
            [self.navigationController pushViewController:det animated:YES];
        }
        
    }else if (indexPath.row == 9){
        JSZViewController *jsz = [[JSZViewController alloc] init];
        NSString *imgUrlZ = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],[_datas objectForKey:@"drivinglicense"]];
        NSString *imgUrlB = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],[_datas objectForKey:@"drivinglicenseback"]];
        jsz.just = imgUrlZ;
        jsz.back = imgUrlB;
        
        [self.navigationController pushViewController:jsz animated:YES];
    }else{
        XSZViewController *xsz = [[XSZViewController alloc] init];
        NSString *imgUrlZ = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],[_datas objectForKey:@"drivingpermitface"]];
        NSString *imgUrlB = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],[_datas objectForKey:@"driveback"]];
        xsz.just = imgUrlZ;
        xsz.back = imgUrlB;
        
        [self.navigationController pushViewController:xsz animated:YES];
    }
    
}

- (void)loadHead{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPicture];
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从相册中获取" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPictureFromAlbum];
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    
    [self presentViewController:alert animated:YES completion:nil];
}

//拍照获取
- (void)pickerPicture{
    if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
        NSLog(@"用前置摄像头");
        imagepc = [[UIImagePickerController alloc] init];
        imagepc.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagepc.delegate = self;
        imagepc.allowsEditing = YES;
        imagepc.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        
    }else if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]){
        NSLog(@"用后置摄像头");
        imagepc = [[UIImagePickerController alloc] init];
        imagepc.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    }else{
        UIAlertController *a = [UIAlertController alertControllerWithTitle:@"调用失败" message:@"请从手机相册中选择" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:a animated:YES completion:nil];
    }
    
    [self presentViewController:imagepc animated:YES completion:nil];
}

//从手机的图片获取
- (void)pickerPictureFromAlbum{
    UIImagePickerController *imgpicker = [[UIImagePickerController alloc] init];
    imgpicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imgpicker.allowsEditing = YES;
    imgpicker.delegate = self;
    [self presentViewController:imgpicker animated:YES completion:nil];
    
}

#pragma -mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    imageView.image = [info objectForKey:UIImagePickerControllerEditedImage];
    //存入相册
    //UIImageWriteToSavedPhotosAlbum(imageView.image, nil, nil, nil);
    [self loadImage];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)loadImage{
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    //上传头像
    UIImage *image = imageView.image;
    
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    NSString *str = [NSString stringWithFormat:@"%@890d69e502d1d37a9e84335ccefece57",[user objectForKey:@"token2"]];
    NSString *token = [LCMD5Tool md5:str];
    [parmas setObject:token forKey:@"verifyToken"];
    [parmas setObject:[user objectForKey:@"userid"] forKey:@"userid"];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = [NSString stringWithFormat:@"%@/App/Usercenter/editUserHeadPortrait",urlHead];
    [manager POST:url parameters:parmas constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        
        fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        [formData appendPartWithFileData:data name:@"headPortrait" fileName:fileName mimeType:@"image/png"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *dics = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
        NSLog(@"dics:%@",dics);
        [LICGToast showWithText:[dics objectForKey:@"msg"]];
        
        [SVProgressHUD dismiss];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD dismiss];
    }];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

